﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Edit.aspx.cs" Inherits="H2.NET.Web.BI.Template.Edit" %>

<%@ Register src="../../UserControls/Toolbar.ascx" tagname="Toolbar" tagprefix="uc1" %>
<script type="text/javascript">
    $(function () {
        $(".clm img", navTab.getCurrentPanel()).hide();
        $(".tb", navTab.getCurrentPanel()).hover(function () {
            $(this).find("img").show();
        }, function () {
            $(this).find("img").hide();
        });
        $(".clm img", navTab.getCurrentPanel()).hover(function () {
            $(this).attr("src", $(this).attr("src").split(".png")[0] + "1.png");
        }, function () {
            $(this).attr("src", $(this).attr("src").split("1.png")[0] + ".png");
        });
        $("#rightWin", navTab.getCurrentPanel()).width($(".pageContent", navTab.getCurrentPanel()).outerWidth() - 232);
        $(".dragUI").dragsort({ dragSelector: "div", dragBetween: false, dragEnd: saveOrder, placeHolderTemplate: "<li class='placeHolder'><div></div></li>" });
        refreshReview();

        var $trash1 = $("#search", navTab.getCurrentPanel());
        var $trash2 = $("#rst,#review", navTab.getCurrentPanel());
        $(".clm", navTab.getCurrentPanel()).draggable({
            helper: "clone",
            cursor: "move"
        });
        $trash1.droppable({
            drop: function (event, ui) {
                var $item = ui.draggable;
                $item.find("img:first").click();
            }
        });
        $trash2.droppable({
            drop: function (event, ui) {
                var $item = ui.draggable;
                $item.find("img:last").click();
            }
        });

    });

    function saveOrder() {
        refreshReview();
    }

    function checkNumber(arg) {
        var val = $(arg).val();
        if ($.trim(val)) {
            if (isNaN(val)) {
                $(arg).val("");
                alertMsg.error("请输入数字！");
            }
        }
    }

    function showCD(arg) {
        $(arg).find("img").show();
        $(".trLi", navTab.getCurrentPanel()).not($(arg)).find("img").hide();
    }

    function hideCD(arg) {
        $(arg).find("img").hide();
    }

    $(window).resize(function () {
        $("#rightWin", navTab.getCurrentPanel()).width($(".pageContent", navTab.getCurrentPanel()).outerWidth() - 342);
    });

    function createDiv(dbName, tbName, columnName, tbShow, columnShow, type, showType) {
        var $dragUI = $("#rst .dragUI:first", navTab.getCurrentPanel());
        if (showType == "2") {
            $dragUI = $("#search .dragUI:first", navTab.getCurrentPanel());
        }
        var size = $dragUI.find("div[title='" + (tbShow + "." + columnShow) + "']").size();
        var showSize = $dragUI.find("div[title$='" + ("." + columnShow) + "']").size();
        if (size == 0 || type == "int" || type == "float" || type == "string") {
            var ss = columnShow;
            //if (showSize > 0) {
                ss = tbShow + "_" + columnShow;
            //}
            if (size > 0 && showType == 1) {
                alertMsg.error("请勿拖放重复字段！");
                return false;
            }
            var baseHtml = "<li><div wd='180' ta='left' ss='" + ss + "' title='" + tbShow + "." + columnShow + "'>" + ss + "</div>" +
                "<img src='../../Resource/Images/lock.png' class='lk' title='自定义筛选' onclick='setLock(this)'/>";
            var textType = "";
            if (type == "int" || type == "float") {
                textType = "number";
                if (size > 0) {
                    baseHtml += "<input type='hidden' class='isOr' />";
                }
                baseHtml += "<select class='lks'><option value='='>等于</option><option value='>'>大于</option><option value='<'>小于</option></select>";
            }
            else if (type == "string") {
                if (size > 0) {
                    baseHtml += "<input type='hidden' class='isOr' />";
                }
                baseHtml += "<select class='lks str'><option value='='>精确</option><option value='like'>模糊</option></select>";
            }
            if (type == "bit") {
                baseHtml += "<select class='lks'><option value=''>全部</option><option value='1'>是</option><option value='0'>否</option></select>";
            }
            else if (type == "datetime") {
                baseHtml += "<input type='text' class='date lkt' readonly size='12' title='请输入开始时间'/> <font class='lkt'>-</font> <input type='text' class='date lkt' readonly size='12' title='请输入结束时间'/>";
            }
            else {
                baseHtml += "<input type='text' size='10' class='lkt " + textType + "' " + (textType == "number" ? "onkeyup='checkNumber(this)'" : "") + " title='请输入筛选条件'/>";
            }
            baseHtml += "<span>" + tbName + "</span><span>" + dbName + "</span><span>" + columnName + "</span><a href='javascript:void(0)' title='删除' onclick='removeDrag(this)'></a></li>";
            if (showType == "1") {
                var asc = false;
                if ($dragUI.find("li").size() == 0) {
                    asc = true;
                }
                baseHtml = "<li><div wd='180' ta='left' ss='" + ss + "' title='" + tbShow + "." + columnShow + "'>" + ss + "</div><span>"
                    + tbName + "</span><span>" + dbName + "</span><span>" + columnName + "</span><select class='hs' onchange='setHS(this)'><option value='0'>可选函数</option><option value='1'>数量</option>";
                if (type == "int" || type == "float") {
                    baseHtml += "<option value='2'>合计</option><option value='3'>平均值</option>";
                }
                baseHtml += "</select><select title='排序' class='stSort' onchange='setST(this)'><option value=''>无</option><option value='asc' " + (asc ? "selected" : "") + ">升</option><option value='desc'>降</option></select>"
                   + "<a href='javascript:void(0)' title='删除' onclick='removeDrag(this)'></a></li>";
                //initReview(ss);
            }
            $dragUI.append(baseHtml);
            if (showType == 1) {
                tzTable($("#rst .dragUI li:last", navTab.getCurrentPanel()));
            }
            $dragUI.initUI();
        }
        
    }

    function setHS(arg) {
        var $li = $("#rst .dragUI div[ss='" + $(arg).siblings("div").attr("ss") + "']").siblings(".hs");
        $li.val($(arg).val()).find("option[value=" + $(arg).val() + "]").attr("selected", "selected").siblings("option").removeAttr("selected");
    }

    function setST(arg) {
        var $li = $("#rst .dragUI div[ss='" + $(arg).siblings("div").attr("ss") + "']").siblings(".stSort");
        $li.val($(arg).val()).find("option[value=" + $(arg).val() + "]").attr("selected", "selected").siblings("option").removeAttr("selected");
    }

    function tzTable(arg) {
        var $li = $(arg).clone();
        $(arg).find(":not(div,a)").hide();
        initReview($li.find("div").attr("ss"), $li.find("div,a").hide().end().html());
    }

    function initReview(tbShow, liCopy) {
        var width = 180;
        var sz = $(".grid", navTab.getCurrentPanel()).find(".viewTR th").size();
        $(".grid", navTab.getCurrentPanel()).find(".viewTR th").each(function () {
            var idx = $(this).index();
            var wd = $(this).outerWidth() * 1;
            $(".viewTB .viewTR", navTab.getCurrentPanel()).find("th:eq(" + idx + ")").css("width", wd);
            width += wd;
        });
        $(".review", navTab.getCurrentPanel()).find(".grid").remove();
        $(".viewTB .viewTR", navTab.getCurrentPanel()).append("<th style='width:180px;' ss='" + tbShow + "' cb='resizeCallBack'>" + tbShow + "<a href='javascript:void(0)' title='删除' class='rth' onclick='removeTH(this)'></a></th>");
        var tal = "<select class='ta' title='对齐方式' onchange='setTA(this)'><option value='left'>左</option><option value='center'>中</option><option value='right'>右</option></select>";
        $(".viewTB .viewCT", navTab.getCurrentPanel()).append("<td style='width:180px;text-align:center' class='dragUI'>" + tal + liCopy + "</td>");
        //else {
        //    $(".viewTB .viewCT", navTab.getCurrentPanel()).append("<td style='width:120px;'>TEST</td>");
        //}
        var $table = $(".viewTB", navTab.getCurrentPanel()).clone();
        $table.css("width", width + 21 + "px");
        $(".review", navTab.getCurrentPanel()).prepend($table.addClass("table").show());
        $table.jTable();
        
    }

    function refreshReview() {
        $(".viewTB .viewTR,.viewTB .viewCT", navTab.getCurrentPanel()).html("");
        var width = 0;
        $(".review", navTab.getCurrentPanel()).find(".grid").remove();
        $("#rst", navTab.getCurrentPanel()).find("li").each(function () {
            var wd = $(this).find("div").attr("wd") * 1;
            var ta = $(this).find("div").attr("ta");
            width += wd;
            var $hs = $(this).find(".hs");
            var $li = $(this).clone();
            $li.find(".hs").html($hs.html());
            var tal = "<select class='ta' title='对齐方式' onchange='setTA(this)'><option value='left' " + (ta == "left" ? "selected" : "") + ">左</option><option value='center' " + (ta == "center" ? "selected" : "")
                + ">中</option><option value='right' " + (ta == "right" ? "selected" : "") + ">右</option></select>";
            $(".viewTB .viewTR", navTab.getCurrentPanel()).append("<th style='width:" + wd + "px;' ss='" + $(this).find("div").attr("ss") + "' cb='resizeCallBack'>" + $(this).find("div").html() + "<a href='javascript:void(0)' title='删除' class='rth' onclick='removeTH(this)'></a></th>");
            $(".viewTB .viewCT", navTab.getCurrentPanel()).append("<td style='width:" + wd + "px;text-align:center' class='dragUI'>" + tal + $li.find(":hidden:not(span)").show().end().find("div,a").hide().end().html() + "</td>");
        });
        var $table = $(".viewTB", navTab.getCurrentPanel()).clone();
        $table.css("width", width + 21 + "px");
        $(".review", navTab.getCurrentPanel()).prepend($table.addClass("table").show());
        $table.jTable();
    }

    function jTableCallback() {
        $(".grid", navTab.getCurrentPanel()).find(".gridScroller").scrollLeft($(".grid", navTab.getCurrentPanel()).find("table").width() - $(".grid", navTab.getCurrentPanel()).width());
        $(".viewTR").find("div").mousedown(function () {
            $(".viewTR").sortable({
                placeholder: "ui-state-highlight",
                start: moveStart(this),
                stop: moveStop
            });
        });
    }

    var $sortObj;
    function moveStart(arg) {
        $sortObj = $(arg).parent();
    }

    function moveStop() {
        var $hidSortObj = $("#rst", navTab.getCurrentPanel()).find("li div[ss=" + $sortObj.attr("ss") + "]").parent();
        if ($sortObj.prev().html()) {
            var $hidPrevObj = $("#rst", navTab.getCurrentPanel()).find("li div[ss=" + $sortObj.prev().attr("ss") + "]").parent();
            $hidSortObj.insertAfter($hidPrevObj);
        }
        else {
            $hidSortObj.parent().prepend($hidSortObj);
        }
        refreshReview();
    }


    function resizeCallBack(arg) {
        var width = $(arg).outerWidth();
        $("#rst .dragUI div[ss='" + $(arg).attr("ss") + "']").attr("wd", width);
    }

    function setTA(arg) {
        var value = $(arg).val();
        //var index = $(arg).parent().parent().parent().find("th").index($(arg).parent().parent());
        //$(".dragUI div[ss='" + $(arg).parent().parent().attr("ss") + "']").attr("ta", value);
        $("#rst .dragUI div[ss='" + $(arg).siblings("div").attr("ss") + "']").attr("ta", value);
        //$(arg).parents(".grid:last").find(".gridScroller").find("td:eq(" + index + ")").css("textAlign", value);
    }

    function initTbls() {
        var tbls = "";
        $(".dragUI li[tp!=1]", navTab.getCurrentPanel()).each(function () {
            var db = $(this).find("span:eq(1)").html();
            var tbl = $(this).find("span:first").html();
            if (tbls.indexOf(db + "." + tbl + ",") < 0) {
                tbls += db + "." + tbl + ",";
            }
        });
        if (tbls && tbls.split(",").length > 1) {
            $.ajax({
                type: 'POST',
                url: "BI/Report/index.aspx?action=initTbls",
                data: { tbls: tbls },
                dataType: "json",
                cache: false,
                async: false,
                success: function (json) {
                    tbls = json.navTabId;
                },
                error: DWZ.ajaxError
            });
            $(".dragUI li[tp!=1]", navTab.getCurrentPanel()).each(function () {
                var db = $(this).find("span:eq(1)").html();
                var tbName = $(this).find("span:first").html();
                if (tbls.indexOf(db + "." + tbName + ",") < 0) {
                    $(this).remove();
                }
            });
        }
        $(".tbls", navTab.getCurrentPanel()).val(tbls);
    }

    function addAll(arg, showType) {
        if (showType == "1") {
            $(arg).parent().parent().next().find(".clm").each(function () {
                $(this).find("img")[1].click();
            });
        } 
        else {
            $(arg).parent().parent().next().find(".clm").each(function () {
                $(this).find("img")[0].click();
            });
        }

    }

    function check(dbName, tbName, columnName, tbShow, columnShow, type, showType) {
        var tbls = $(".tbls", navTab.getCurrentPanel()).val();
        if (tbls.indexOf(dbName + "." + tbName + ",") < 0) {
            if (!$.trim(tbls)) {
                $(".tbls", navTab.getCurrentPanel()).val(tbls += dbName + "." + tbName + ",");
                createDiv(dbName, tbName, columnName, tbShow, columnShow, type, showType);
            } else {
            $.ajax({
                type: 'POST',
                url: "BI/Report/index.aspx?action=check",
                data: { tbls: tbls, tname: dbName + "." + tbName },
                dataType: "json",
                cache: false,
                success: function (json) {
                    if (json.statusCode == 200) {
                        tbls += dbName + "." + tbName + ",";
                        $(".tbls", navTab.getCurrentPanel()).val(tbls);
                        createDiv(dbName, tbName, columnName, tbShow, columnShow, type, showType);
                    } else {
                        alertMsg.error("字段：" + columnShow + " 与已选择的表没有任何关联，无法添加！");
                    }
                },
                error: DWZ.ajaxError
            });
            }
        } else {
            createDiv(dbName, tbName, columnName, tbShow, columnShow, type, showType);
        }
    }

    var errorInfo = "";
    function init() {
        errorInfo = "";
        //查询字段
        var data = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () { return $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + " '" + $(this).find("div").text() + "'"; }).get();
        $(".rst", navTab.getCurrentPanel()).val(data.join(","));
        //各字段宽度
        var widths = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () { return $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "|" + $(this).find("div").attr("wd"); }).get();
        $(".widths", navTab.getCurrentPanel()).val(widths.join(","));
        //各自段对其方式
        var ta = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () { return $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "|" + $(this).find("div").attr("ta"); }).get();
        $(".tas", navTab.getCurrentPanel()).val(ta.join(","));
        //查询字段中文别名
        var cnData = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () { return "["+$(this).find("div").text()+"]"; }).get();
        $(".cnRst", navTab.getCurrentPanel()).val(cnData.join(","));
        //数量字段
        var count = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () {
            var val = $(this).find(".hs").val();
            if (val == "1") {
                var sm = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html();
                return sm;
            } else {
                return "";
            }
        }).get();
        $(".count", navTab.getCurrentPanel()).val(count.join(","));
        //合计字段
        var sum = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () {
            var val = $(this).find(".hs").val();
            if (val=="2") {
                var sm = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html();
                return sm;
            } else {
                return "";
            }
        }).get();
        $(".sum", navTab.getCurrentPanel()).val(sum.join(","));
        //平均值字段
        var avg = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () {
            var val = $(this).find(".hs").val();
            if (val == "3") {
                var sm = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html();
                return sm;
            } else {
                return "";
            }
        }).get();
        $(".avg", navTab.getCurrentPanel()).val(avg.join(","));
        //需要显示的查询条件
        var search = $("#search .dragUI li[tp!=1]", navTab.getCurrentPanel()).not(":has(img[src$='1.png'])").map(function () {
            return $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html();
        }).get();
        $(".search", navTab.getCurrentPanel()).val(search.join(","));
        //固定不显示的条件
        var where = "";
        var fixedResult = "";
        var isOr = false;
        var temp = "";
        var tempW = "";
        $("#search .dragUI li[tp!=1]", navTab.getCurrentPanel()).has("img[src$='1.png']").each(function () {
            var whereResult = "";
            //bit
            if ($(this).find(":text").size() == 0) {
                var selectVal = $(this).find("select").val();
                if (selectVal) {
                    fixedResult += $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "|" + "=" + "|" + selectVal + ",";
                    whereResult = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "=" + selectVal;
                }
            }
                //数字和字符串
            else if ($(this).find(":text").size() == 1) {
                var selectVal = $(this).find("select").val();
                var val = $(this).find(":text").val();
                if ($.trim(val)) {
                    var tempVal = val;
                    if ($(this).find("select").hasClass("str")) {
                        if ($(this).find("select").val() == "like") {
                            val = "'%" + val + "%'";
                        }
                        else {
                            val = "'" + val + "'";
                        }
                    }
                    fixedResult += $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "|" + selectVal + "|" + tempVal + ",";
                    whereResult = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + " " + selectVal + " " + val;
                }
                else {
                    errorInfo = "请填写完整固定查询的条件！";
                }
            }
                //日期
            else if ($(this).find(":text").size() == 2) {
                var tempType = "";
                var tempValue = "";
                var val1 = $(this).find(":text:first").val();
                var val2 = $(this).find(":text:last").val();
                if (!$.trim(val1) || !$.trim(val2)) {
                    errorInfo = "请填写完整固定查询的条件！";
                }
                if ($.trim(val1) || $.trim(val2)) {
                    if ($.trim(val1)) {
                        tempType += ">=";
                        tempValue += $.trim(val1);
                        whereResult += $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + ">='" + $.trim(val1) + "'";
                    }
                    if ($.trim(val2)) {
                        if (whereResult) {
                            whereResult += " and ";
                            tempType += "、";
                            tempValue += "、";
                        }
                        tempType += "<=";
                        tempValue += $.trim(val2);
                        whereResult += $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "<='" + $.trim(val2) + "'";
                    }
                    fixedResult += $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html() + "|" + tempType + "|" + tempValue + ",";
                }
            }
            if (whereResult) {
                if (where) {
                    var osize = $(this).find(".isOr").size();
                    var od = " and ";
                    if (osize > 0) {
                        od = " or ";
                        if (tempW == " and " || tempW == "") {
                            where = where.replace(temp, "(" + temp);
                        } else {
                            if (tempW == " or ") {
                                where = where.substring(0, where.length - 1);
                            }
                        }
                        whereResult = whereResult + ")";
                    }
                    tempW = od;
                    where += od + whereResult;
                }
                else {
                    where += whereResult;
                }
                temp = whereResult;
            }
        });
        if (where.indexOf(",") >= 0) {
            alertMsg.error("查询内容不允许带有逗号 \",\"");
            return false;
        }
        $(".fixed", navTab.getCurrentPanel()).val(fixedResult);
        $(".where", navTab.getCurrentPanel()).val(where);
        //排序字段
        var tempSort = "";
        var sort = $("#rst .dragUI li[tp!=1]", navTab.getCurrentPanel()).map(function () {
            var val = $(this).find(".stSort").val();
            var order = "nullSort";
            if (val) {
                order = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html();
                order += " " + val;
            }
            return order;
            //var src = $(this).find(".od").attr("src");
            //var order = $(this).find("span:eq(1)").html() + "." + $(this).find("span:first").html() + "." + $(this).find("span:last").html();
            //if (tempSort.indexOf("[" + order + "]") < 0) {
            //    tempSort += "[" + order + "]";
            //    if (src.indexOf("sort") >= 0) {
            //        return "nullSort";
            //    }
            //    else if (src.indexOf("asc") >= 0) {
            //        order += " asc";
            //    }
            //    else if (src.indexOf("desc") >= 0) {
            //        order += " desc";
            //    }
            //}
            //else {
            //    order = "nullSort";
            //}
            //return order;
        }).get();
        var sortResult = sort.join(",");
        if (!sortResult || !sortResult.replaceAll(",", "").replaceAll("nullSort", "")) {
            if ($(".tbls", navTab.getCurrentPanel()).val()) {
                var $dl = $("#rst .dragUI li[tp!=1]:first", navTab.getCurrentPanel());
                sortResult = $dl.find("span:eq(1)").html() + "."
                    + $dl.find("span:first").html() + "." + $dl.find("span:last").html() + " asc";
            }
        }
        $(".sort", navTab.getCurrentPanel()).val(sortResult);
    }

    function removeDrag(arg) {
        $(arg).parent().remove();
        refreshReview();
        initTbls();
    }


    function removeTH(arg) {
        var ss = $(arg).parent().parent().attr("ss");
        var $rstObj = $("#rst", navTab.getCurrentPanel()).find("li div[ss=" + ss + "]");
        removeDrag($rstObj);
    }

    //function setSort(arg) {
    //    var src = $(arg).attr("src");
    //    if (src.indexOf("sort") >= 0) {
    //        $(arg).attr("src", "../../Resource/Images/asc.png").attr("title", "升序");
    //    }
    //    else if (src.indexOf("asc") >= 0) {
    //        $(arg).attr("src", "../../Resource/Images/desc.png").attr("title", "降序");
    //    }
    //    else if (src.indexOf("desc") >= 0) {
    //        $(arg).attr("src", "../../Resource/Images/sort.png").attr("title", "无排序");
    //    }
    //    $("#rst .dragUI div[ss='" + $(arg).siblings("div").attr("ss") + "']").siblings("img").attr("src", $(arg).attr("src")).attr("title", $(arg).attr("title"));
    //}

    function setSum(arg) {
        var src = $(arg).attr("src");
        if (src.indexOf("sum1") >= 0) {
            $(arg).attr("src", "../../Resource/Images/sum.png").attr("title", "不计算合计值");
        }
        else {
            $(arg).attr("src", "../../Resource/Images/sum1.png").attr("title", "计算合计值");
        }
    }

    function setLock(arg) {
        var src = $(arg).attr("src");
        if (src.indexOf("lock1") >= 0) {
            $(arg).attr("src", "../../Resource/Images/lock.png").attr("title", "自定义筛选");
            $(arg).nextAll(":text,select,font").val("").hide();
        }
        else {
            $(arg).attr("src", "../../Resource/Images/lock1.png").attr("title", "固定筛选");
            $(arg).nextAll(":text,select,font").show();
        }
    }

    function OwnerExec(url, rel, title) {
        init();
        if (errorInfo) {
            alertMsg.error(errorInfo);
            return false;
        }
        var tbls = $(".tbls", navTab.getCurrentPanel()).val();
        var rst = $(".rst", navTab.getCurrentPanel()).val();
        var sum = $(".sum", navTab.getCurrentPanel()).val();
        var count = $(".count", navTab.getCurrentPanel()).val();
        var avg = $(".avg", navTab.getCurrentPanel()).val();
        var sort = $(".sort", navTab.getCurrentPanel()).val();
        var search = $(".search", navTab.getCurrentPanel()).val();
        var cnRst = $(".cnRst", navTab.getCurrentPanel()).val();
        var where = $(".where", navTab.getCurrentPanel()).val();
        var widths = $(".widths", navTab.getCurrentPanel()).val();
        var ta = $(".tas", navTab.getCurrentPanel()).val();
        if (!tbls || !rst) {
            alertMsg.error("请选择需要显示的字段！");
            return false;
        }
        navTab.openTab("tempQuery", url, { title: "预览查询", data: { tbls: tbls, rst: rst, ta:ta,sum: sum, count: count, avg: avg, sort: sort, where: where, search: search, widths: widths, cnRst: cnRst } });
        return false;
    }

    function OwnerSave(url, rel, title) {
        var tbls = $(".tbls", navTab.getCurrentPanel()).val();
        if (!tbls) {
            alertMsg.error("请选择需要显示的字段！");
            return false;
        }
        $.pdialog.open(url + "?id=<%:id%>&cp=<%:cp%>", rel, title, { width: 400, height: 200, mask: true });
        return false;
    }

    function saveTemplate() {
        var name = $("#temName", $(".dialog:last")).val();
        var pub = "false";
        if ($(".isPub:checked", $(".dialog:last")).size() > 0) {
            pub = $(".isPub:checked", $(".dialog:last")).val();
        }
        var group = $("#txt_cfg_group", $(".dialog:last")).val();
        $.pdialog.closeCurrent();
        init();
        if (errorInfo) {
            alertMsg.error(errorInfo);
            return false;
        }
        var tbls = $(".tbls", navTab.getCurrentPanel()).val();
        var rst = $(".rst", navTab.getCurrentPanel()).val();
        var sum = $(".sum", navTab.getCurrentPanel()).val();
        var count = $(".count", navTab.getCurrentPanel()).val();
        var avg = $(".avg", navTab.getCurrentPanel()).val();
        var sort = $(".sort", navTab.getCurrentPanel()).val();
        var search = $(".search", navTab.getCurrentPanel()).val();
        var cnRst = $(".cnRst", navTab.getCurrentPanel()).val();
        var where = $(".where", navTab.getCurrentPanel()).val();
        var widths = $(".widths", navTab.getCurrentPanel()).val();
        var fixed = $(".fixed", navTab.getCurrentPanel()).val();
        var ta = $(".tas", navTab.getCurrentPanel()).val();
        if (!tbls || !rst) {
            alertMsg.error("请选择需要显示的字段！");
            return false;
        }
        $.ajax({
            type: 'POST',
            url: "BI/Report/save.aspx?action=save",
            data: { id: "<%:string.IsNullOrEmpty(cp)?id:0%>", tempId: "<%:!string.IsNullOrEmpty(cp)?id:0%>", fixed: fixed, ta: ta, name: name, pub: pub, group: group, tbls: tbls, rst: rst, sum: sum, count: count, avg: avg, sort: sort, where: where, search: search, widths: widths, cnRst: cnRst },
            dataType: "json",
            cache: false,
            success: function (json) {
                var cp = "<%:cp%>";
                if (json.navTabId) {
                    var $pt = $("#myRPT");
                    var tid = json.navTabId.split("|")[0];
                    var tname = json.navTabId.split("|")[1];
                    if (cp) {
                        var rpt = "<li><div><div class='line'></div><div class='node'></div><div class='file'></div><a rpt='" + tid + "' style='color:green;' "
                       + "href='BI/Template/Exec.aspx?id=" + tid + "&amp;mid=46' target='navTab' rel='" + tname + "'>" + tname + "</a></div></li>";
                        $pt.append(rpt);
                        initUI($pt);
                    } else {
                        $("a[rpt=" + tid + "]").attr("rel", tname).html(tname);
                    }
                }
                alertMsg.correct("保存成功！");
            },
            error: DWZ.ajaxError
        });
    }

    function trashAll(id) {
        $("#" + id, navTab.getCurrentPanel()).find(".dragUI li[tp!=1]").not(":hidden").remove();
        if (id == "rst") {
            refreshReview();
        } 
        initTbls();
    }
</script>
<style type="text/css">
    #leftWin {
        width:200px;border-right:2px solid #b8d0d6;float:left;padding:3px;padding-left:10px;float:right;
    }
    #rightWin {
        float:right;
    }
    #leftWin .tb,.db {
        font-weight:bold;margin-bottom:3px;
    }
    #leftWin .clm {
        padding-left:85px;margin-top:-1px;margin-bottom:3px;cursor:default;*padding-left:0px;*display:inline;*zoom:1;*width:50%;*margin-top:-4px;
    }
    #leftWin .clm img{
        margin-top:-4px;*margin-top:0px;
    }
    #leftWin .tree .folder_collapsable,.tree .folder_expandable{
        background:url(../../Resource/Images/mdc_table.png) no-repeat;
    }
    #leftWin .tree > li > div > .folder_collapsable, .tree > li > div > .folder_expandable {
    background:url(../../Resource/Images/mdc_db.png) no-repeat;
    }
    #leftWin .tree .file {
        background:url(../../Resource/Images/mdc_column.png) no-repeat;
    }
    #leftWin .tree .trLi,#leftWin .tree .trLi a{
        cursor:move;
    }
    #rightWin .dragUI {
        list-style-type:none; 
    }
    #rightWin .dragUI li {
        float:left;margin:5px;border:1px solid #b8d0d6;cursor:pointer;height:27px;*white-space:pre;
    }

    #rightWin .dragUI a {
       display:inline-block;width:11px;height:11px;margin:1px;top:-5px;*top:-14px;position:relative;background:url(../../Resource/dwz/themes/default/images/tabs/tabspage_icon.png) no-repeat;
    }
    #rightWin .dragUI input {
        float:right;margin-left:5px;margin-top:2px;cursor:pointer;
    }
    #rightWin .dragUI img {
        width: 16px;height: 16px;display: inline-block;cursor:pointer;border:none;margin-left:3px;margin-top:-4px;*margin-top:-8px;margin-right:3px;
    }
    #rightWin .dragUI img.od {
        width:20px;   
    }
    #rightWin .dragUI a:hover {
        background-position-y:-50px;
    }
    #rightWin .dragUI div {
        display:inline-block;*display:inline;*zoom:1;padding:8px 20px 5px 5px;*white-space:pre;
    }
    #rightWin .dragUI span {
        display:none;
    }
    .placeHolder div { background-color:white !important; border:dashed 1px gray !important;width:50px;height:15px; }

    #leftWin .tree li img {
        margin-right:0px;padding:3px;cursor:pointer;
    }
    #leftWin .tb
    {
        padding-left:0px;
    }
    .trash {
        margin-left:5px;padding:0px 5px;margin-top:-4px;cursor:pointer
    }
    #rightWin .dragUI li .lk {
        margin-top:-5px;*margin-top:-10px;margin-right:3px;
    }
    #rightWin .dragUI li .lkt{
        display:none;float:none;margin-right:3px;
    }
    #rightWin .dragUI li .lks {
        display:none;float:none;margin-left:5px;
    }
   
     #rightWin .tzWidth {
        border-right:1px solid red;width:5px;height:28px;display:inline-block;cursor:e-resize;position:absolute;
    }
    #rightWin .viewCT div {
        padding-left:0px;padding-right:0px;width:180px;*height:40px;
    }
    #rightWin .gridScroller{
        overflow-y:hidden;
    }
    #rightWin .selected{
        background-color:white;
    }
    #rightWin .viewTR .rth {
        display:inline-block;width:11px;height:11px;margin:1px;margin-left:3px;*top:-5px;position:relative;background:url(../../Resource/dwz/themes/default/images/tabs/tabspage_icon.png) no-repeat;
    }
    #rightWin .viewTR .rth:hover {
        background-position-y:-50px;
    }
    #rightWin .ui-state-highlight{
        background: #ffe45c;
	    color: #363636;
    }
</style>
<form id="form1" runat="server">
<div class="pageContent">
	<div class="panelBar" style="margin-top:-1px">
		<ul class="toolBar">
		    <uc1:toolbar ID="Toolbar1" runat="server" />
		</ul>
	</div>
	<div id="rightWin" layouth="26">
        
       
         <div class="panel" defH="200" id="search">
		    <h1>查询显示字段<img class="trash" src="../../Resource/Images/trash.png" title="清空" onclick="trashAll('search')"/></h1>
            <div style="background:white;">
                <ul class="dragUI">
			        <%
                        List<string> tbls = new List<string>();
                        List<string> colName = new List<string>();
                        List<string> orList = new List<string>();
                        var textType = "";
                        foreach (var detail in template.bi_TemplateDetail.Where(b=>b.filter==true || b.fix == true))
                        {
                            var fullName = detail.bi_Column.bi_Table.bi_DB.name + ".dbo." + detail.bi_Column.bi_Table.table_name;
                            if (!tbls.Contains(fullName))
                            {
                                tbls.Add(fullName);
                            }
                            var ss = detail.bi_Column.name_cn;
                            //if (colName.Contains(ss))
                            //{
                                ss = detail.bi_Column.bi_Table.name_cn + "_" + detail.bi_Column.name_cn;
                           // }
                            orList.Add(ss);
                            colName.Add(ss);
                            var tp = false;
                            if ((detail.fix == true && !string.IsNullOrEmpty(cp))||detail.hide==true)
                            {
                                tp = true;
                            }
                            if (tp && template.create_user != clsCmm.comm_username)
                            {%>
                              <li tp="1" style="border:1px solid #b8d0d6;margin:5px;">
                                  <div  title='<%:detail.bi_Column.bi_Table.name_cn + "." + detail.bi_Column.name_cn %>'>
                                      <%:ss %>
                                  </div>
                                  <img src='../../Resource/Images/lock1.png' class='lk' title='自定义筛选' />
                                  <%
                                if (detail.type.IndexOf("、") >= 0)
                                {%>
                                    <div style="padding-right:5px;"><%:detail.type.Split('、')[0] %></div>
                                    <div style="padding-right:5px;"><%:detail.value.Split('、')[0] %></div>
                                    <div style="padding-right:5px;">and</div>
                                    <div style="padding-right:5px;"><%:detail.type.Split('、')[1] %></div>
                                    <div style="padding-right:5px;"><%:detail.value.Split('、')[1] %></div>
                                <%}
                                else {  
                                  %>
                                  <div style="padding-right:5px;"><%:detail.type %></div>
                                  <div style="padding-right:5px;"><%:detail.value %></div>
                                  <%} %>
                              </li>  
                            <%}
                        %>
                          <li <%:tp&&template.create_user!=clsCmm.comm_username?"style=display:none":"" %>>
                              <div wd='<%:detail.width %>' ss='<%:ss %>' title='<%:detail.bi_Column.bi_Table.name_cn + "." + detail.bi_Column.name_cn %>'><%:ss %></div>
                              <img src='../../Resource/Images/lock<%:detail.fix==true?"1":"" %>.png' class='lk' title='<%:detail.fix==true?"固定筛选":"自定义筛选" %>' onclick='setLock(this)'/>  
                              <%
                                if (detail.bi_Column.type == "int" || detail.bi_Column.type == "float")
                                {
                                    textType = "number";
                                    if (orList.Where(o => o == ss).Count() > 1)
                                    {%>
                                      <input type="hidden" class="isOr"/>  
                                    <%}
                                    %>
                                    <select class='lks' <%:detail.fix==true?"style=display:inline-block":"" %>><option value='=' <%:detail.type=="="?"selected":"" %>>等于</option><option value='>' <%:detail.type==">"?"selected":"" %>>大于</option><option value='<' <%:detail.type==">"?"selected":"" %>>小于</option></select>
                                <%}
                                else if (detail.bi_Column.type == "string")
                                {
                                    if (orList.Where(o => o == ss).Count() > 1)
                                    {%>
                                      <input type="hidden" class="isOr"/>  
                                    <%}    
                                %>
                                    <select class='lks str' <%:detail.fix==true?"style=display:inline-block":"" %>><option value='=' <%:detail.type=="="?"selected":"" %>>精确</option><option value='like' <%:detail.type=="like"?"selected":"" %>>模糊</option></select>
                                <%}
                                if (detail.bi_Column.type == "bit")
                                {%>
                                    <select class='lks' <%:detail.fix==true?"style=display:inline-block":"" %>><option value=''>全部</option><option value='1' <%:detail.value=="1"?"selected":"" %>>是</option><option value='0' <%:detail.value=="0"?"selected":"" %>>否</option></select>
                                <%}
                                else if (detail.bi_Column.type == "datetime")
                                {
                                    var value = detail.value==null?"":detail.value;
                                    %>
                                    <input <%:detail.fix==true?"style=display:inline-block":"" %> value="<%:value.IndexOf("、")>=0?value.Split('、')[0]:value %>" type='text' class='date lkt' readonly size='12' title='请输入开始时间'/> 
                                    <font <%:detail.fix==true?"style=display:inline-block":"" %> class='lkt'>-</font> 
                                    <input <%:detail.fix==true?"style=display:inline-block":"" %> value="<%:value.IndexOf("、")>=0?value.Split('、')[1]:"" %>" type='text' class='date lkt' readonly size='12' title='请输入结束时间'/>
                                <%}
                                else
                                {%>
                                    <input <%:detail.fix==true?"style=display:inline-block":"" %> value="<%:detail.value %>" type='text' size='10' class='lkt <%:textType %>' <%:textType== "number" ? "onkeyup='checkNumber(this)'" : "" %> title='请输入筛选条件'/>
                                <%}%>
                              <span><%:detail.bi_Column.bi_Table.table_name %></span><span><%:detail.bi_Column.bi_Table.bi_DB.name+".dbo" %></span>
                              <span><%:detail.bi_Column.column_name %></span><a href='javascript:void(0)' title='删除' onclick='removeDrag(this)'></a></li>
                        <%}%>
		        </ul>
            </div>
	    </div>

        <div class="panel" defH="76" id="review">
		    <h1>快速预览 & 样式调整<img class="trash" src="../../Resource/Images/refresh.png" title="刷新" onclick="refreshReview()"/></h1>
            <div style="background:white;padding-top:0px;overflow:hidden;" class="review">
                <table class="viewTB" style="display:none;">
                    <thead>
                        <tr class="viewTR">
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="viewCT">
                        </tr>
                    </tbody>
                </table>
            </div>
	    </div>

        <div class="panel" defH="190" id="rst" style="display:none">
		    <h1>报表显示字段<img class="trash" src="../../Resource/Images/trash.png" title="清空" onclick="trashAll('rst')"/></h1>
            <div style="background:white;">
                <ul class="dragUI">
			        <%
                        colName = new List<string>();
                        foreach (var detail in template.bi_TemplateDetail.Where(b => b.filter == false && b.fix == false))
                        {
                            var fullName = detail.bi_Column.bi_Table.bi_DB.name + ".dbo." + detail.bi_Column.bi_Table.table_name;
                            if (!tbls.Contains(fullName))
                            {
                                tbls.Add(fullName);
                            }
                            var ss = detail.bi_Column.name_cn;
                            if (colName.Contains(ss))
                            {
                                ss = detail.bi_Column.bi_Table.name_cn + "_" + detail.bi_Column.name_cn;
                            }
                            colName.Add(ss);
                    %>
                            <li><div wd='<%:detail.width %>' ta="<%:detail.textAlign %>" ss='<%:ss %>' title='<%:detail.bi_Column.bi_Table.name_cn + "." + detail.bi_Column.name_cn %>'><%:ss %></div>
                                <span><%:detail.bi_Column.bi_Table.table_name %></span><span><%:detail.bi_Column.bi_Table.bi_DB.name+".dbo" %></span><span><%:detail.bi_Column.column_name %></span>
                                <select class="hs" style="display:none" onchange='setHS(this)'>
                                    <option value="0" <%:detail.func==0?"selected":"" %>>可选函数</option>
                                    <option value="1" <%:detail.func==1?"selected":"" %>>数量</option>
                                    <%
                                    if(detail.bi_Column.type=="int"||detail.bi_Column.type=="float")
                                    {%>
                                        <option value="2" <%:detail.func==2?"selected":"" %>>合计</option>
                                        <option value="3" <%:detail.func==3?"selected":"" %>>平均值</option>
                                    <%}    
                                 %>
                                </select>
                                <select class="stSort" onclick="setST(this)">
                                    <option value="">无</option>
                                    <option value="asc" <%:detail.sort=="asc"?"selected":"" %>>升</option>
                                    <option value="desc" <%:detail.sort=="desc"?"selected":"" %>>降</option>
                                </select>
                               <%-- <img  style="display:none" src='../../Resource/Images/<%:detail.sort=="asc"?"asc":(detail.sort=="desc"?"desc":"sort") %>.png' class='od' title='无排序' onclick='setSort(this)'/>--%>
                                <a href='javascript:void(0)' title='删除' onclick='removeDrag(this)'></a></li>
                       <%}%>
		        </ul>
            </div>
	    </div>

        

        <%--<div class="panel" defH="100" id="chart">
		    <h1>图表显示字段<img class="trash" src="../../Resource/Images/trash.png" title="清空" onclick="trashAll('chart')"/></h1>
            <div style="background:white;">
                <ul class="dragUI">
			    
		        </ul>
            </div>
	    </div>--%>
		<%
            var tbs = "";
            if (tbls.Count() > 0)
            {
                foreach (var tbl in tbls)
                {
                    tbs += tbl + ",";
                }
            }
        %>
        <input name="tables" type="hidden" class="tbls" value="<%:tbs%>"/>
        <input name="result" type="hidden" class="rst" />
        <input name="cnRst" type="hidden" class="cnRst" />
        <input name="sum" type="hidden" class="sum" />
        <input name="count" type="hidden" class="count" />
        <input name="avg" type="hidden" class="avg" />
        <input name="sort" type="hidden" class="sort" />
        <input name="search" type="hidden" class="search" />
        <input name="where" type="hidden" class="where" />
        <input name="fixed" type="hidden" class="fixed" />
        <input name="widths" type="hidden" class="widths" />
        <input name="ta" type="hidden" class="tas" />
        <%--<div id="reportInfo" style="margin-top:-5px;"></div>--%>
	</div>
    <div id="leftWin" layouth="33">
        <ul class="tree treeFolder expand" style="width:300px;">
        <%
            foreach (var db in DB)
            {%>
                <li><a href="javascript:void(0)" class="db"><%:db.name%></a>
                <ul>
                    <%
                    foreach (var table in db.bi_Table)
                    {%>
                        <li><a href="javascript:void(0)" class="tb clm">
                                <img src='../../Resource/Images/search.png' title='【<%:table.name_cn%>】所有字段加入查询显示' onclick="addAll(this,'2')"/>
                                <img src='../../Resource/Images/rst.png' title='【<%:table.name_cn%>】所有字段加入报表显示' onclick="addAll(this,'1')"/>
                                <span style="display:inline-block"><%:table.name_cn%></span></a>
                            <ul>
                                <%
                                    foreach (var column in table.bi_Column.Where(c=>c.show == true).ToList())
                                    {%>
                                        <li class="trLi">
                                            <a href="javascript:void(0)" class="clm" >
                                                <img src='../../Resource/Images/search.png' title='【<%:column.name_cn%>】 加入查询显示' onclick="check('<%:table.bi_DB.name+".dbo" %>','<%:table.table_name %>','<%:column.column_name %>','<%:table.name_cn %>','<%:column.name_cn%>','<%:column.type %>','2')"/>
                                                <img src='../../Resource/Images/rst.png' title='【<%:column.name_cn%>】 加入报表显示' onclick="check('<%:table.bi_DB.name+".dbo" %>','<%:table.table_name %>','<%:column.column_name %>','<%:table.name_cn %>','<%:column.name_cn%>','<%:column.type %>','1')"/>
                                                <span style="display:inline-block"><%:column.name_cn%></span>
                                                <%--<img src='../../Resource/Images/chart1.png' title='字段【<%:column.name_cn%>】 加入图表显示' onclick="check('<%:table.table_name %>','<%:column.column_name %>','<%:table.name_cn %>','<%:column.name_cn%>','<%:column.type %>','3')"/>--%>
                                            </a>
                                        </li>
                                    <%}
                                %>
                            </ul>
                        </li>
                    <%}%>
                </ul>
            <%}%>
            
        </ul>
    </div>
</div>
</form>
